"use strict";

/**
 * Web访问相关
 */
//------------------------------------------------------------------
import {ElMessage} from "element-plus";
import vbUtils from "../js/util"
//------------------------------------------------------------------

export default class Axios {
    constructor(axios, router) {
        let self = this
        axios.defaults.timeout = 6000000;
        axios.defaults.baseURL = import.meta.env.VITE_APP_URL;

        axios.interceptors.request.use(config => {
            return self.request(config)
        }, e => {
            ElMessage.error(e.message || e.err || e);
            return {result: false};
        });
        axios.interceptors.response.use(res => {
            return self.response(res)
        }, e => {
            ElMessage.error(e.message || e.err || e);
            return {result: false};
        })

        this.axios = axios
        this.router = router
    }

    /**
     * 响应拦截器
     * @param res
     * @returns {*}
     */
    response = (res) => {
        let self = this
        if (res.config.responseType === 'blob') return res;
        if (!res.data.res) {
            if (res.data.code === "E_not_login") {
                sessionStorage.removeItem("token")
                self.router.replace({
                    name: "/login",
                    query: {}
                })
            } else {
                ElMessage.error(res.data.err);
            }
            throw res.data.err
        }
        return res;
    }

    /**
     * 请求拦截器
     * @param config
     * @returns {*}
     */
    request = (config) => {
        if ( sessionStorage.token ) {
            config.headers.vt = sessionStorage.token;
        }

        if (config.data) {
            if(config.data.$type === 'upload') {
                config.headers["Content-Type"] = "multipart/form-data";
                let form = new FormData();
                for (let key in config.data.data) {
                    if (config.data.data[key]) {
                        let v = config.data.data[key]
                        if (v instanceof Array) {
                            let dataList = v;
                            for(let i = 0; i < dataList.length; i++) {
                                form.append(key, dataList[i]);
                            }
                        } else {
                            form.append(key, v);
                        }
                    }
                }
                config.data = form;
            } else if (config.data.$type === 'download') {
                config.responseType = 'blob';
                config.data = config.data.data
            }
        }
        return config;
    }

    /**
     * get方式访问API
     * @param url 路由
     * @param data 参数
     */
    get = (url, data = {}) => {
        let self = this
        return new Promise((resolve, reject) => {
            self.axios.get(url, {
                params: data
            }).then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
        })
    };

    /**
     * post方式访问API
     * @param url 路由
     * @param data 参数
     */
    post = (url, data = {}) => {
        let self = this
        return new Promise((resolve, reject) => {
            self.axios.post(url, data).then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
        })
    };

    /**
     * put方式访问API
     * @param url 路由
     * @param data 参数
     */
    put = (url, data = {}) => {
        let self = this
        return new Promise((resolve, reject) => {
            self.axios.put(url, data).then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
        })
    };

    /**
     * delete方式访问API
     * @param url 路由
     * @param data 参数
     */
    delete = (url, data = {}) => {
        let self = this
        return new Promise((resolve, reject) => {
            self.axios.delete(url, {
                data: data
            }).then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
        })
    };

    /**
     * 上传文件
     * @param url 路由
     * @param data 参数
     */
    upload = (url, data = {}) => {
        let self = this
        return new Promise((resolve, reject) => {
            self.axios.post(url, {
                data: data,
                $type: "upload"
            }).then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
        })
    };

    /**
     * Download方式访问API
     *
     * @param url 路由
     * @param data 参数
     */
    download(url, data = {}) {
        let self = this;
        return new Promise((resolve, reject) => {
            self.axios.post(url, {
                data: data,
                $type: "download"
            }).then(response => {
                let fileName = response.headers["vtuzx-filename"];
                if (fileName) {
                    // 下载成功
                    let res = { res: true, data: response.data, filename: decodeURIComponent(fileName) };
                    // if (!manual) {
                    vbUtils.download(res);
                    // }
                    resolve(res);
                } else {
                    // 下载失败
                    if (response.request) {
                        let reader = new FileReader();
                        reader.onload = e => {
                            let content = JSON.parse(e.target.result);
                            if (!content.res) ElMessage.error(content.err);
                            reject(content);
                        };
                        reader.readAsText(response.data);
                    } else {
                        if (!response.data.res) ElMessage.error(response.data.err);
                        reject(response.data);
                    }
                }
            }, err => {
                reject(err)
            })
        })
    }
}
